package cn.zzdt4j.config.toolkit;

import java.util.concurrent.ConcurrentHashMap;

/**
 * The type Singleton repository.
 *
 * @param <T> the type parameter
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023 /11/8 15:23
 */
public class SingletonRepository<T> {

    /**
     * initialCapacity: 1 << 16
     */
    private static final int INITIAL_CAPACITY = 65536;

    public SingletonRepository() {
        shared = new ConcurrentHashMap<>(INITIAL_CAPACITY);
    }

    public T getSingleton(T obj) {
        T previous = shared.putIfAbsent(obj, obj);
        return (null == previous) ? obj : previous;
    }

    public int size() {
        return shared.size();
    }

    public void remove(Object obj) {
        shared.remove(obj);
    }

    private final ConcurrentHashMap<T, T> shared;

    /**
     * Data Id Group Id Cache
     */
    public static class DataIdGroupIdCache {

        public static String getSingleton(String str) {
            return cache.getSingleton(str);
        }

        static SingletonRepository<String> cache = new SingletonRepository<String>();
    }
}
